#include <boot/boot.h>
#include <pub.h>
#include <draw.h>
#include <printk.h>
#include <intr/idt.h>
#include <asm/cpuid.h>
#include <mem/mem.h>
#include <mem/page.h>
#include <asm/gdt.h>
#include <asm/tss.h>
#include <asm/asm.h>


void EnjoySystem(void)
{
       // 初始化打印方法
       if (init_draw(COLOR_YELLOW, COLOR_BLACK))
       {
              while (1)
                     ;
       }
       printk("display init completed\n");

       //初始化中断
       TssVal.ist1 = KERNEL_BASE + IST_BASE_ADDR; // 中断栈1(128K)
       TssVal.ist2 = KERNEL_BASE + IST_BASE_ADDR; // 中断栈2(128K)
       TssVal.ist3 = KERNEL_BASE + IST_BASE_ADDR; // 中断栈3(128K)
       TssVal.ist4 = KERNEL_BASE + IST_BASE_ADDR; // 中断栈4(128K)
       TssVal.ist5 = KERNEL_BASE + IST_BASE_ADDR; // 中断栈5(128K)
       TssVal.ist6 = KERNEL_BASE + IST_BASE_ADDR; // 中断栈6(128K)
       TssVal.ist7 = KERNEL_BASE + IST_BASE_ADDR; // 中断栈7(128K)
       
       // TssVal.rsp2 = sys_stack + KERNEL_BASE; // DPL=2时的堆栈(128K)
       // TssVal.rsp1 = sys_stack + KERNEL_BASE; // DPL=1时的堆栈(128K)
       TssVal.rsp0 = STACK_64_ADDR + KERNEL_BASE; // DPL=0时的堆栈

       init_interrupt();
       LOAD_TR(TSS_SELECTOR_IDX);
       
       
       // 初始化内存分布结构
       if (mem_init() != 0)
       {
              while (1)
                     ;
       }
       printk("memory struct completed\n");


       printk("pitch=%u,bpp=%u,width=%u,height=%u,attr=%u,size=%u,addr=%p\n",
              __vbe_info.pitch, __vbe_info.bpp, __msg.width,
              __msg.height, __vbe_info.attributes, __vbe_info.off_screen_mem_size, __msg.addr);

       printk("cupid base num:[%d]<==>ext num:[%d]<==>"
              "maxphyaddr:[%d]<==>ed flag:[%x]\n"
              "is supported long mode:[%x]<==>"
              "is supported 1G Page:[%d]<==>"
              "pcids:[%d]<==>gdt:[0x%lx]<==>mem count[%u]\n",
              query_base(), query_base(),
              max_phy_addr(), is_enable_xd(), check_long_mod(),
              is_enable_1g_page(), check_pcids(), GdtTable, __mem_map.size);
       
       printk("ist1=%lx,ist2=%lx, ist3=%lx,rsp0=%lx,rsp1=%lx,rsp2=%lx\n",
              TssVal.ist1, TssVal.ist2, TssVal.ist3, TssVal.rsp0,
              TssVal.rsp1, TssVal.rsp2);

       printk("tss low:0x%lx\ttss_high:0x%lx\n", GdtTable[TSSINDEX], GdtTable[TSSINDEX+1]);
 


#ifdef BOCHS_DEBUG_POINT
       __asm__ __volatile__("xchgw %bx, %bx");
#endif
       // draw_rect(COLOR_WHITE, 80, 80, 50, 50);
       // draw_rect(COLOR_WHITE, 0, 0, 50, 50);
       __asm__ __volatile__("1: \n\t"
                            "hlt\n\t"
                            "xorq %rax, %rax\n\t"
                            "xorq %rax, %rax\n\t"
                            "xorq %rax, %rax\n\t"
                            "nop\n\t"
                            "jmp 1b");
}
